package mysql

import (
	"gorm.io/gorm"
)

type Goods struct {
	gorm.Model
	GoodsTitle  string `gorm:"type:varchar(50);not null;comment:商品标题"`
	GoodsPrice  int64  `gorm:"not null;comment:商品价格"`
	GoodsStock  int64  `gorm:"not null;comment:商品库存"`
	GoodsCover  string `gorm:"type:varchar(255);comment:商品封面"`
	GoodsStatus int8   `gorm:"not null;comment:商品状态"`
}

//创建

func (g *Goods) Create() error {
	return Db.Create(&g).Error
}

//获取商品列表

func (g *Goods) GetList(page, size int) (goods []*Goods, err error) {
	db := Db
	err = db.Scopes(Paginate(page, size)).Find(&goods).Error
	if err != nil {
		return nil, err
	}
	return goods, nil
}

//分页展示

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

//获取商品详情

func (g *Goods) GetInfo(id int) (*Goods, error) {
	err = Db.Where("id = ?", id).Find(&g).Error
	if err != nil {
		return nil, err
	} else {
		return g, nil
	}
}
